<template>
    <div>
        <!-- seach区域 -->
        <div class="seach">
            <span>
                {{$t('rolenam')}}
                <el-input v-model.trim="role.roleName" :placeholder="$t('plsipt')" size="mini"></el-input>
            </span>
            <!-- <span class="seachStatus">
                {{$t('sta')}}
                <el-select v-model="stateOptions" :placeholder="$t('plsset')" size="mini">
                    <el-option :label="'-' + $t('plsset') + '-'" :value="null"></el-option>
                    <el-option :label="$t('vlid')" value="VALID"></el-option>
                    <el-option :label="$t('invlid')" value="INVALID"></el-option>
                </el-select>
            </span> -->
            <el-button type="primary" @click="getRole" size="mini" v-preventReClick>{{$t('qury')}}</el-button>
            <el-button type="warning" @click="showAddRole" size="mini" v-preventReClick>{{$t('addrole')}}</el-button>
        </div>
        <!-- 内容区域 -->
        <el-card class="cardBox">
            <el-table border style="width: 100%" :data="roleTab">
                <el-table-column type="index" :label="$t('sernum')">
                </el-table-column>
                <el-table-column prop="roleName" :label="$t('rolenam')" min-width="135">
                </el-table-column>
                <el-table-column prop="roleCode" :label="$t('roleval')" min-width="137">
                </el-table-column>
                <el-table-column prop="status" :label="$t('sta')" min-width="110">
                </el-table-column>
                <el-table-column prop="address" :label="$t('opratn')" width="140">
                    <template slot-scope="scope">
                        <el-link type="primary" @click="showEditRole(scope.row.roleId)">{{$t('mdfy')}}</el-link>
                        <el-link type="primary" @click="showPower(scope.row)">{{$t('permag')}}</el-link>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="role.pageNum"
                :page-sizes="[10, 15, 20, 30]"
                :page-size="role.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                :pager-count="5">
            </el-pagination>
        </el-card>
        <!-- 添加弹框 -->
        <el-dialog :title="$t('add')" :visible.sync="addDialogVisible" width="30%" @close="addDialogVisibleClosed(addRoleForm)" :close-on-click-modal='isOk' :modal-append-to-body="false">
            <el-form :ref="addRoleForm" :rules="addRoleRul" :model="addRoleForm" label-width="80px" :hide-required-asterisk="true">
                <el-form-item :label="$t('rolenam')" prop="roleName">
                    <el-input v-model.trim="addRoleForm.roleName" :placeholder="$t('plsipt')"></el-input>
                </el-form-item>
                <el-form-item :label="$t('roleval')" prop="roleCode">
                    <el-input v-model.trim="addRoleForm.roleCode" :placeholder="$t('plsipt')"></el-input>
                </el-form-item>
                <!-- <el-form-item :label="$t('sta')" prop="status">
                    <el-select v-model="addRoleForm.status" :placeholder="$t('plsset')" class="sellong">
                        <el-option :label="$t('vlid')" value="VALID"></el-option>
                        <el-option :label="$t('invlid')" value="INVALID"></el-option>
                    </el-select>
                </el-form-item> -->
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="addRole(addRoleForm)" v-preventReClick>{{$t('cfm')}}</el-button>
                <el-button @click="addDialogVisible = false" v-preventReClick>{{$t('cnl')}}</el-button>
            </span>
        </el-dialog>
        <!-- 修改弹框 -->
        <el-dialog :title="$t('mdfy')" :visible.sync="editDialogVisible" width="30%" @close="editDialogVisibleClosed(editRoleForm)" :close-on-click-modal='isOk' :modal-append-to-body="false">
            <el-form :ref="editRoleForm" :rules="editRoleRul" :model="editRoleForm" label-width="80px" :hide-required-asterisk="true">
                <el-form-item :label="$t('rolenam')" prop="roleName">
                    <el-input v-model.trim="editRoleForm.roleName" :placeholder="$t('plsipt')"></el-input>
                </el-form-item>
                <el-form-item :label="$t('roleval')" prop="roleCode">
                    <el-input v-model.trim="editRoleForm.roleCode" :placeholder="$t('plsipt')"></el-input>
                </el-form-item>
                <el-form-item :label="$t('sta')" prop="status">
                    <el-select v-model="editRoleForm.status" :placeholder="$t('plsset')" class="sellong">
                        <el-option :label="$t('vlid')" value="VALID"></el-option>
                        <el-option :label="$t('invlid')" value="INVALID"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="editRole(editRoleForm)" v-preventReClick>{{$t('cfm')}}</el-button>
                <el-button @click="editDialogVisible = false" v-preventReClick>{{$t('cnl')}}</el-button>
            </span>
        </el-dialog>
        <!-- 权限框 -->
        <el-dialog :title="$t('permag')" :visible.sync="powerDialogVisible" width="30%" @close="powerDialogVisibleClosed" :modal-append-to-body="false">
            <el-tree :data="powerForm" show-checkbox :ref="powerForm" node-key="funcId" :default-checked-keys="selForm" default-expand-all></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="editPower(powerForm)" v-preventReClick>{{$t('cfm')}}</el-button>
                <el-button @click="powerDialogVisible = false" v-preventReClick>{{$t('cnl')}}</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {
    rolelist,
    roleadd,
    roleeditdet,
    roleedit,
    powertree,
    powertreeedit
} from '@/libs/reqlist.js'
export default {
    data () {
        return {
            isOk: false,
            // 总条数
            total: 0,
            // seach rolename
            role: {
                roleName: '',
                pageNum: 1,
                pageSize: 10
            },
            // user seach state
            seachState: '',
            // 选择状态
            stateOptions: '',
            // 角色列表
            roleTab: [],
            // addBox show and hide
            addDialogVisible: false,
            // 添加表单数据
            addRoleForm: {
                roleId: '',
                roleName: '',
                roleCode: '',
                status: 'VALID'
            },
            // 添加表单验证规则
            addRoleRul: {
                roleName: [
                    { required: true, message: this.$t('rolenamectemy'), trigger: 'blur' }
                ],
                roleCode: [
                    { required: true, message: this.$t('rolevalctemy'), trigger: 'blur' }
                ],
                status: [
                    { required: true, message: this.$t('rolestacntbeemt'), trigger: 'blur' }
                ]
            },
            // editBox show and hide
            editDialogVisible: false,
            // 修改表单数据
            editRoleForm: {
                roleName: '',
                roleCode: '',
                status: '',
                roleId: ''
            },
            // 修改表单规则
            editRoleRul: {
                roleName: [
                    { required: true, message: this.$t('rolenamectemy'), trigger: 'blur' }
                ],
                roleCode: [
                    { required: true, message: this.$t('rolevalctemy'), trigger: 'blur' }
                ],
                status: [
                    { required: true, message: this.$t('rolestacntbeemt'), trigger: 'blur' }
                ]
            },
            // power show and hide
            powerDialogVisible: false,
            powerForm: [],
            // 选中的权限列表
            funcIds: [],
            func: {
                funcIds: [],
                userID: ''
            },
            defKeys: [],
            selForm: []
        }
    },
    methods: {
        getRole () {
            this.role.pageNum = 1
            this.seachRole()
        },
        // 查询角色
        async seachRole () {
            await rolelist(JSON.stringify(this.role)).then(res => {
                if (res.data.code === '000000') {
                    this.total = res.data.data.total - 0
                    // this.role.pageSize = res.data.data.pageSize
                    this.roleTab = res.data.data.list
                    this.roleTab.forEach(item => {
                        if (item.status === 'VALID') item.status = this.$t('vlid')
                        if (item.status === 'INVALID') item.status = this.$t('invlid')
                        // item.sysGmtCreate = item.sysGmtCreate.substring(0, 10)
                        // item.sysGmtModified = item.sysGmtModified.substring(0, 10)
                    })
                }
            })
        },
        // 监听页面展示数据条数变化
        handleSizeChange (newSize) {
            this.role.pageSize = newSize
            this.seachRole()
        },
        // 监听总页数变化
        handleCurrentChange (newNum) {
            this.role.pageNum = newNum
            window.localStorage.setItem('curpage', newNum)
            this.seachRole()
        },
        // 展示添加角色框
        showAddRole () {
            this.addDialogVisible = true
        },
        // 添加角色
        addRole (form) {
            this.$refs[form].validate(async valid => {
                if (!valid) return
                this.addRoleForm.roleId = this.total + 1
                await roleadd(JSON.stringify(this.addRoleForm)).then(res => {
                    if (res.data.code === '999902') {
                        this.$message.error(this.$t('duproleid'))
                        return false
                    }
                    if (res.data.code === '992103') {
                        this.$message.error(this.$t('rolevalexs'))
                        return false
                    }
                    this.$message({
                        message: this.$t('addrolesuc'),
                        type: 'success'
                    })
                    this.seachRole()
                    this.addDialogVisible = false
                })
            })
        },
        // 添加框关闭触发
        addDialogVisibleClosed (form) {
            this.$refs[form].resetFields()
        },
        // 展示修改角色框
        showEditRole (id) {
            roleeditdet(id).then(res => {
                this.func.userID = id
                this.editRoleForm = res.data.data
                if (this.editRoleForm.status === 'INVALID') this.editRoleForm.status = this.$t('invlid')
                if (this.editRoleForm.status === 'VALID') this.editRoleForm.status = this.$t('vlid')
            })
            this.editDialogVisible = true
        },
        editRole (form) {
            this.$refs[form].validate((valid) => {
                if (!valid) {
                    return false
                }
                this.editRoleForm.roleId = this.func.userID
                if (this.editRoleForm.status === this.$t('vlid')) this.editRoleForm.status = 'VALID'
                if (this.editRoleForm.status === this.$t('invlid')) this.editRoleForm.status = 'INVALID'
                roleedit(JSON.stringify(this.editRoleForm)).then(res => {
                    if (res.data.code === '050001') {
                        this.$message.error(this.$t('Inuserrights'))
                        this.editDialogVisible = false
                    }
                    if (res.data.code === '000000') {
                        this.editDialogVisible = false
                        this.seachRole()
                        this.$message({
                            message: this.$t('rolemodsuc'),
                            type: 'success'
                        })
                    }
                })
            })
        },
        // 关闭重置
        editDialogVisibleClosed (form) {
            this.$refs[form].resetFields()
        },
        // 展示权限框
        async showPower (role) {
            await powertree(role.roleId).then(res => {
                if (res.data.code === '000000') {
                    res.data.data.forEach(item => {
                        item.label = item.funcName
                        item.children.forEach(item => {
                            item.label = item.funcName
                            item.children.forEach(item => {
                                item.label = item.funcName
                            })
                            this.getLeafKeys(item, this.defKeys)
                        })
                    })
                    this.powerForm = res.data.data
                    this.defKeys.forEach(item => {
                        if (item.flag === true) {
                            this.selForm.push(item.funcId)
                        }
                    })
                }
            })
            this.func.userID = role.roleId
            this.powerDialogVisible = true
        },
        // 修改权限
        async editPower (form) {
            let keys = [
                ...this.$refs[form].getCheckedKeys(),
                ...this.$refs[form].getHalfCheckedKeys()
            ]
            this.func.funcIds = keys
            await powertreeedit(this.func.userID, JSON.stringify(this.func)).then(res => {
                if (res.data.code === '000000') {
                    this.$message({
                        message: this.$t('modfunsuc'),
                        type: 'success'
                    })
                }
                this.powerDialogVisible = false
            })
        },
        getLeafKeys(node, arr) {
            // 如果当前节点不包括children属性,就是三级节点
            if (node.children.length === 0) {
                return arr.push({ funcId: node.funcId, flag: node.flag })
            }
            // 到这里就表示不是三级路由,循环下面的children
            node.children.forEach(item => this.getLeafKeys(item, arr))
        },
        powerDialogVisibleClosed () {
            this.defKeys = []
            this.selForm = []
        }
    },
    mounted () {
        if (window.localStorage.getItem('curpage')) this.role.pageNum = window.localStorage.getItem('curpage') - 0
        this.seachRole()
    },
    destroyed () {
        if (window.localStorage.getItem('curpage')) window.localStorage.removeItem('curpage')
    }
}
</script>

<style lang="less" scoped>
@import './rolemgr.less';
</style>
